#!/usr/bin/perl

require JSON;

my $apikey = "2bc44df8-e988-4a64-ae11-cc3a8d4d048e";
#my $userid = "36765399";
my $userid = "22843654";
my $tmpfile = "/tmp/lolstats." . $userid;
my $champid = "9";  ## looking for fiddlesticks history.  Fiddle = champid 9

sub main {
#	print "hi\n";
	get_stats($userid);
	return 0;
}

sub get_stats {
	my $id = $_[0];
	my $cmd = "curl --request GET 'https://na.api.pvp.net/api/lol/na/v2.2/matchhistory/$userid?api_key=$apikey'";
	print "trying cmd: $cmd\n";
	open (CMD, "$cmd |") or die "$!: Could not open cmd: $cmd\n";
	open (TMP, "> $tmpfile" ) or die "Could not open out file: $tmpfile\n";
	my $txt;
	#open (CMD, "/home/jday/LoL/userdata.json") or die "$!: Could not open file\n";
	while (<CMD>) {
		my $line = trim($_);
		print TMP "$line\n";
		$txt .= "$line\n";
	}

	my $json = JSON->new();
#	my $ref = $xs->XMLin($xmltxt);
	my $ref = $json->decode($txt);

	my $use = 0;
	my $total = 0;
	my $won = 0;
	foreach my $top (sort(keys( %{$ref} ))) {
		print "top: $top\n";
		print "val: ${$ref}{$top}\n";
		foreach my $match ( @{${$ref}{$top}} ) {
			foreach my $var (sort(keys( %{$match} ))) {
				print "var: $var, val: ${$match}{$var}\n";
				if ( defined$var && $var eq "participants" ) {
					foreach my $parth ( @{${$match}{$var}} ) {
						foreach my $part (sort(keys( %{$parth} ))) {
							print "\tparticipant: $part ${$parth}{$part}\n";
							if ( defined $part && $part eq "championId" && defined ${$parth}{$part} && ${$parth}{$part} eq $champid ) {
								$total++;
							}
							if ( defined $part && $part eq "stats" ) {
								foreach my $stat (sort(keys( %{${$parth}{$part}} ))) {
									print "\t\tstat: $stat, val: ${$parth}{$part}{$stat}\n";
									if ( defined $stat && $stat eq "winner" && defined ${$parth}{$part}{$stat} && ${$parth}{$part}{$stat} eq "true" ) {
										$won++;
									}
								}
							}
						}
					}
				}
			}
			print "\n"
		}
	}

	if ( defined $total && $total > 0 ) {
		print "Total:\n";
		print "$won / $total\n";
		my $perc = sprintf("%.2d", 100 * ( $won / $total) );
		print "Percent: $perc\n";
	} else {
		print "no games found with fiddle :(\n";
	}

}


sub trim {
	my $in = $_[0];
	my $out = $in;
	$out =~ s/\n|\r$//g;
	return $out;
}

exit main();


### get userinfo  
### curl --request GET 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/zzzmaestro?api_key=2bc44df8-e988-4a64-ae11-cc3a8d4d048e' --include
